//
//  ReservationListViewController.m
//  homeland
//
//  Created by SunShine on 13-10-29.
//  Copyright (c) 2013年 xzysun. All rights reserved.
//

#import "ReservationListViewController.h"
#import "ReservationListCell.h"
#import "ReservationViewController.h"
#import "ReservationRecordListViewController.h"

@interface ReservationListViewController ()
@property (strong, nonatomic) ReservationService *dataService;
@property (strong, nonatomic) CustomPullToRefresh *ptr;
@end

@implementation ReservationListViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"政务服务中心";
    self.navigationItem.rightBarButtonItem = rightNavBtnWithImgName(@"预约记录", self, @selector(rightButtonAction:));
    self.dataService = [ReservationService new];
    _dataService.delegate = self;
    _searchBar.delegate = self;
    _searchBar.inputAccessoryView = [self getInputAccessoryView];
    //开启下拉刷新
    self.ptr = [[CustomPullToRefresh alloc]initWithScrollView:self.tableView delegate:self];
    //如果传入了搜索值，写到这个页面的搜索框里面
    _searchBar.text = _searchKey;
    [self startLoadingView];
    [_dataService requestReservationListForCode:_unitCode AndSearchkey:_searchKey];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Buttons
-(void)rightButtonAction:(id)sender
{
    NSLog(@"点击了预约记录");
    ReservationRecordListViewController *listVC = [[ReservationRecordListViewController alloc] initWithNibName:@"ReservationRecordListViewController" bundle:nil];
    [self.navigationController pushViewController:listVC animated:YES];
}

-(void)reservationButtonAction:(id)sender
{
    UIButton *bt = (UIButton *)sender;
    NSLog(@"点击了第%d行的预约",bt.tag);
    ReservationListItem *item = [_dataService.dataList objectAtIndex:bt.tag];
    ReservationViewController *vc = [[ReservationViewController alloc] initWithNibName:@"ReservationViewController" bundle:nil];
    vc.listItem = item;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - Table
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_dataService.dataList count];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 66.0;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ReservationListCell *cell = [[[NSBundle mainBundle] loadNibNamed:@"ReservationListCell" owner:self options:nil] objectAtIndex:0];
    ReservationListItem *item = [_dataService.dataList objectAtIndex:indexPath.row];
    cell.nameLabel.text = item.showName;
    cell.reservationButton.tag = indexPath.row;
    [cell.reservationButton addTarget:self action:@selector(reservationButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}


#pragma mark - Data Service
-(void)loadDataFinished
{
    [self stopLoadingView];
    [self.ptr endRefresh];
    [_tableView reloadData];
}

-(void)loadDataFaild:(NSString *)msg
{
    [self stopLoadingView];
    [self.ptr endRefresh];
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:msg delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
    [alert show];
}

-(void)setEnableToLoadMore:(BOOL)enable
{
    self.ptr.enablePullToBottom = enable;
}

#pragma mark - PullToRefresh Method
//捕获到拉动事件
-(void)customPullToRefreshShouldRefresh:(CustomPullToRefresh *)ptr withDirection:(MSRefreshDirection)direction
{
    NSLog(@"捕获到拉动事件");
    if (direction == MSRefreshDirectionTop) {
        [self.dataService requestReservationListForCode:_unitCode AndSearchkey:_searchKey];
    }
    if (direction == MSRefreshDirectionBottom) {
        [self.dataService requestMoreReservationListForCode:_unitCode AndSearchkey:_searchKey];
    }
}

#pragma mark - Search Bar Delegate
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    NSLog(@"search bar input:%@",searchText);
}

-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    NSLog(@"search button clicked with input:%@",searchBar.text);
    [searchBar resignFirstResponder];
}

static BOOL onceReturn;
-(void)searchBarTextDidEndEditing:(UISearchBar *)searchBar
{
    NSLog(@"search bar end edit with input %@",searchBar.text);
    if (searchBar.text.length == 0) {
        if (self.unitCode) {
            [self startLoadingView];
            [_dataService requestReservationListForCode:_unitCode AndSearchkey:nil];
        } else {
            //如果没有部门类型，清理搜索框就返回上一级页面
//            [self.navigationController popViewControllerAnimated:YES];
            if (!onceReturn) {//因为键盘的退出机制会导致这里调用两次pop,所以这里做一个控制防止多次pop引起异常崩溃
                onceReturn = YES;
                [self.navigationController popViewControllerAnimated:YES];
            }
        }
    } else {
        [_dataService requestReservationListForCode:_unitCode AndSearchkey:searchBar.text];
    }
}
@end
